package com.wl.day74.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.wl.day74.biz.BookBiz;
import com.wl.day74.biz.BookTypeBiz;
import com.wl.day74.model.AjaxMsgModel;
import com.wl.day74.model.BookType;
import com.wl.day74.model.Books;
import com.wl.day74.util.Constants;

@Controller
@RequestMapping("/books")
public class BookAction extends BaseAction {
	@Autowired
	private BookBiz bookBiz;
	@Autowired
	private BookTypeBiz bookTypeBiz;
	
	@RequestMapping("list")
	public void list(Map<String, Object> map){
		List<Books> bookList = bookBiz.findAll();
		map.put("bookList", bookList);
	}
	
	@RequestMapping("add")
	public String add(Map<String, Object> map){
		List<BookType> bookTypeList = bookTypeBiz.findAll();
		map.put("bookTypeList", bookTypeList);
		if(!map.containsKey("book")){
			map.put("book", new Books());
		}
		return "books/add";
	}
	
	@ResponseBody
	@RequestMapping("save")
	public AjaxMsgModel save(Books book, HttpServletRequest request){
		RequestContext ctx = new RequestContext(request);
		try {
			bookBiz.saveOrUpdate(book);
			return getJsonModel(Constants.STATUS_CODE_SUCCESS, ctx.getMessage("operateSuccess"), "main", true);
		} catch (Exception e) {
			return this.getJsonModel(Constants.STATUS_CODE_FAIL, ctx.getMessage("operateFail"), "main", true);
		}
	}
	
	@ResponseBody
	@RequestMapping("delete/{bookId}")
	public AjaxMsgModel delete(@PathVariable Integer bookId, HttpServletRequest request){
		RequestContext ctx = new RequestContext(request);
		try {
			bookBiz.delById(bookId);
			return getJsonModel(Constants.STATUS_CODE_SUCCESS, ctx.getMessage("operateSuccess"), "main", true);
		} catch (Exception e) {
			e.printStackTrace();
			return getJsonModel(Constants.STATUS_CODE_FAIL, ctx.getMessage("operateFail"), "main", true);
		}
	}
	
	@RequestMapping("update")
	public String update(Books book, Map<String, Object> map){
		book = bookBiz.findById(book.getBookId());
		map.put("book", book);
		return add(map);
	}
	

	/**********************getter and setter************************************/
	public void setBookBiz(BookBiz bookBiz) {
		this.bookBiz = bookBiz;
	}
	public void setBookTypeBiz(BookTypeBiz bookTypeBiz) {
		this.bookTypeBiz = bookTypeBiz;
	}
}
